package com.cnxdc.demo.interceptors;

import com.cnxdc.demo.utils.JwtUtil;
import com.cnxdc.demo.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中拿到token进行解析，不报错则成功！
        String token = request.getHeader("Authorization");
        try {
            Map<String, Object> map = JwtUtil.parseToken(token);
            String username =(String) map.get("username");
            //读取redis中的token 判断是否相同
            String tok = (String) redisTemplate.opsForValue().get(username);
            if (!tok.equals(token)) {
                // 响应401：未授权
                response.setStatus(401);
                return false;
            }
            ThreadLocalUtil.set(map);//塞入到 ThreadLocalUtil中
            return true;//不抛异常则放行
        } catch (Exception e) {
            // 响应401：未授权
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //释放掉TL中的数据，以防止爆内存!!!
        ThreadLocalUtil.remove();
    }
}
